package com.raspberryCar.service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import com.pi4j.io.i2c.I2CFactory.UnsupportedBusNumberException;
import com.pi4j.util.Console;
import com.raspberryCar.model.Camera;
import com.raspberryCar.model.Car;
import com.raspberryCar.model.SmallCar;


public class SocketService{
	
	public static void main(String[] args) throws IOException,
			UnsupportedBusNumberException {
//		Car car = Car.getInstance();
		SmallCar car = SmallCar.getInstance();
		Camera camera = Camera.getInstance();
		ServerSocket serverSocket = new ServerSocket(10086);// 1024-65535的某个端口
		// 2、调用accept()方法开始监听，等待客户端的连接
		System.out.println("Service 启动,等待连接");
		Socket socket = null;
		InputStream is = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		Console console = new Console();

		while (!console.exiting()) {
			socket = serverSocket.accept();
			// 3、获取输入流，并读取客户端信息
			is = socket.getInputStream();
			isr = new InputStreamReader(is);
			br = new BufferedReader(isr);
			String info = null;
			try {
				
			
			while ((info = br.readLine()) != null) {
				if (info.equals("left")) {
					System.out.println("left");
					car.left();
				} else if (info.equals("right")) {
					System.out.println("right");
					car.right();
				} else if (info.equals("ret")) {
					System.out.println("ret");
					car.ret();
				} else if (info.equals("faw")) {
					System.out.println("faw");
					car.faw();
				} else if (info.equals("stop")) {
					System.out.println("stop");
					car.stop();
				} 
				else if (info.equals("fast")) {
					System.out.println("fast");
					car.fast();
				} 
				else if (info.equals("slow")) {
					System.out.println("slow");
					car.slow();
				}else if (info.equals("camRight")) {
					System.out.println("camRight");
					camera.right();
				}else if (info.equals("camLeft")) {
					System.out.println("camLeft");
					camera.left();
				}else if (info.equals("camUp")) {
					System.out.println("camUp");
					camera.up();
				}else if (info.equals("camDown")) {
					System.out.println("camDown");
					camera.down();
				} else {
					System.out.println("我是服务器，客户端说：" + info);
				}

			}
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("连接断开");
			}
		}

		socket.shutdownInput();// 关闭输入流
		// 4、获取输出流，响应客户端的请求
		OutputStream os = socket.getOutputStream();
		PrintWriter pw = new PrintWriter(os);
		pw.write("Service down");
		pw.flush();

		// 5、关闭资源
		pw.close();
		os.close();
		br.close();
		isr.close();
		is.close();
		socket.close();
		serverSocket.close();
	}
}
